package com.dingding.common.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 
 * @ClassName: DataUtil 
 * @Description:手机客户端数据交互类
 * @author cheshaowei
 * @date 2015-7-3 上午09:14:44 
 * @version 叮叮搭车V2.0
 * 
 */
public class DataUtil {

	private static final Logger log = Logger.getLogger(DataUtil.class);

	/**
	 * 
	 * @Title: getData
	 * @Description: 获取手机端传输过来的数据
	 * @param dataJson
	 *            手机端返回的JSON数据
	 * @author cheshaowei
	 * @return void
	 * @throws
	 */
	public final static String getData(HttpServletRequest httpServletRequest) {
		// 输入流
		InputStream inputStream = null;
		// 输入字符流
		InputStreamReader inputStreamReader = null;
		// 字符缓冲流
		BufferedReader bufferedReader = null;
		try {

			inputStream = httpServletRequest.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			bufferedReader = new BufferedReader(inputStreamReader);
			// 读取字符
			String readLine = bufferedReader.readLine();
			StringBuffer buffer = new StringBuffer();
			while (readLine != null) {
				buffer.append(readLine);
				readLine = bufferedReader.readLine();
			}

			return buffer.toString();

		} catch (IOException e) {
			log.error("获取输入流出现错误！DataUtil中的getData()方法", e);
			return null;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					log.error("关闭缓冲流出现异常！", e);
				}
			}
			if (inputStreamReader != null) {
				try {
					inputStreamReader.close();
				} catch (IOException e) {
					log.error("关闭字符流出现异常！", e);
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					log.error("关闭输入流出现异常！", e);
				}
			}
		}
	}

	/**
	 * 
	 * @Title: write
	 * @Description: 输出数据给手机客户端
	 * @param data
	 *            服务端返回给手机端的数据
	 * @author cheshaowei
	 * @return void
	 * @throws
	 */
	public final static void dataWrite(HttpServletResponse httpServletResponse, String data) {

		try {

			// 输出数据到手机客户端
			httpServletResponse.getWriter().print(data);
			httpServletResponse.getWriter().flush();
			httpServletResponse.getWriter().close();

		} catch (IOException e) {
			log.error("返回数据到手机客户端出现异常！DataUtil中的write()方法", e);
		}

	}
}
